/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.institution.approval;

import com.alibaba.fastjson.JSONObject;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.institution.bean.InstitutionFile;
import com.koron.institution.bean.InstitutionFileHistory;
import com.koron.institution.mapper.InstitutionFileHistoryMapper;
import com.koron.institution.mapper.InstitutionFileMapper;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.List;

public class InstitutionEditService implements AfterApprovalService {

    private final static  Logger logger = LoggerFactory.getLogger(InstitutionAddService.class);

    InstitutionFileHistory translateInstitutionToHistory(InstitutionFile institutionFile) throws Exception {
        InstitutionFileHistory history = new InstitutionFileHistory();
        BeanUtils.copyProperties(institutionFile, history);
        history.setId(DefaultIdGenerator.getInstance().generateLongId());
        return history;
    }

    InstitutionFile translateHistoryToInstitution(InstitutionFileHistory history) throws Exception {
        InstitutionFile institutionFile = new InstitutionFile();
        BeanUtils.copyProperties(history, institutionFile);
        institutionFile.setState(0);
        institutionFile.setReviseState(0);
        institutionFile.setId(DefaultIdGenerator.getInstance().generateLongId());
        return institutionFile;
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            InstitutionFileHistoryMapper historyMapper = factory.getMapper(InstitutionFileHistoryMapper.class);
            InstitutionFileMapper mapper = factory.getMapper(InstitutionFileMapper.class);
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && idList.size() > 0) {
                for (String id : idList) {
                    if (StringUtils.isNotBlank(id)) {
                        InstitutionFileHistory history = historyMapper.selectByPrimaryKey(id);
                        if (history != null) {
                            if (StringUtils.isNotBlank(history.getCode())) {
                                InstitutionFile institutionFile = mapper.queryInstitutionByCode(history.getCode()).get(0);
                                InstitutionFileHistory historyNew = translateInstitutionToHistory(institutionFile);
                                historyNew.setHistoryFlag(1);
                                historyNew.setState(0);
                                //添加原文件的历史记录
                                historyMapper.insert(historyNew);
                                //删除原文件
                                mapper.deleteByPrimaryKey(institutionFile.getId());
                                //将修订后文件插入列表
                                //判断名称是否重复
                                InstitutionFile institutionFileNew = translateHistoryToInstitution(history);
                                InstitutionFile sameNameIns = mapper.getInstitutionByFileName(institutionFileNew);
                                if (sameNameIns != null && !sameNameIns.getCode().equals(institutionFileNew.getCode())) {
                                    changeName(mapper, institutionFileNew, 1);
                                }
                                mapper.insert(institutionFileNew);
                                history.setState(0);
                                historyMapper.updateByPrimaryKeySelective(history);
                            }
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            InstitutionFileHistoryMapper historyMapper = factory.getMapper(InstitutionFileHistoryMapper.class);
            InstitutionFileMapper mapper = factory.getMapper(InstitutionFileMapper.class);
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && idList.size() > 0) {
                for (String id : idList) {
                    if (StringUtils.isNotBlank(id)) {
                        InstitutionFileHistory history = historyMapper.selectByPrimaryKey(id);
                        if (history != null) {
                            List<InstitutionFile> institutionFiles = mapper.queryInstitutionByCode(history.getCode());
                            if (institutionFiles != null && !institutionFiles.isEmpty()) {
                                for (InstitutionFile ins : institutionFiles) {
                                    if (ins.getState() == 2) {
                                        ins.setState(0);
                                        mapper.updateByPrimaryKeySelective(ins);
                                    }
                                }
                            }
                            history.setState(4);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    private void changeName(InstitutionFileMapper mapper, InstitutionFile institutionFileNew, int i) {
        String name = institutionFileNew.getFileName() + i;
        institutionFileNew.setFileName(name);
        InstitutionFile sameNameIns = mapper.getInstitutionByFileName(institutionFileNew);
        if (sameNameIns != null && !sameNameIns.getCode().equals(institutionFileNew.getCode())) {
            changeName(mapper, institutionFileNew, i++);
        }
    }


    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
